var createError = require('http-errors');
var express = require('express');
const formidable = require('formidable');
var path = require('path');
var cookieParser = require('cookie-parser'); 
var logger = require('morgan');
const db = require('./model/db')
const fs = require('fs')
const cors = require("cors")

// 引入界面路由
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// var mainRouter = require('./routes/main');

var app = express();

app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  next();
});

const User = require('./model/admin/User')
User.create({
  username: 'admin',
  password: 'admin'
}, (err)=>{
  if (!err) {
    console.log('创建成功')
  }
})


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// 使用界面路由
app.use('/', indexRouter);
app.use('/users', usersRouter);

// 后台首页
app.get('/main',(req,res)=>{
  res.set('')
  res.render('main', { title: '山西旅游网站管理系统' });
})



// ------ADMIN-------
app.post('/user/login',require('./api/admin/login'))

// 获取用户列表
app.get('/tourist/list', require('./api/tourist/list'))

// 查询用户
app.get('/tourist/search', require('./api/tourist/search'))

// 删除用户
app.post('/tourist/del', require('./api/tourist/del'));

// 添加用户
app.post('/tourist/add', require('./api/tourist/add'));

// 用户登录
app.post('/tourist/login', require('./api/tourist/login'));


// 用户修改
app.post('/tourist/change', require('./api/tourist/change'));


// -----scenicSpot--------

app.post('/scenicSpot/add', require('./api/scenicSpot/add'))
app.post('/scenicSpot/change', require('./api/scenicSpot/change'))
app.get('/scenicSpot/search', require('./api/scenicSpot/search'))
app.get('/scenicSpot/getData', require('./api/scenicSpot/getData'))
app.post('/scenicSpot/del', require('./api/scenicSpot/del'))
app.get('/scenicSpot/list', require('./api/scenicSpot/list'))
app.get('/scenicSpot/getChange', require('./api/scenicSpot/getChange'))



// -----Tour---------

app.post('/tour/add', require('./api/tour/add'))
app.post('/tour/change', require('./api/tour/change'))
app.get('/tour/search', require('./api/tour/search'))
app.post('/tour/del', require('./api/tour/del'))
app.get('/tour/list', require('./api/tour/list'))
app.get('/tour/getChange', require('./api/tour/getChange'))



// -----route--------

app.post('/route/add', require('./api/route/add'))
app.post('/route/change', require('./api/route/change'))
app.get('/route/search', require('./api/route/search'))
app.post('/route/del', require('./api/route/del'))
app.get('/route/list', require('./api/route/list'))
app.get('/route/getChange', require('./api/route/getChange'))
app.get('/route/getData', require('./api/route/getData'))



// -----order-----
app.get('/order/list', require('./api/order/list'))
app.post('/order/add', require('./api/order/add'))
app.get('/order/search', require('./api/order/search'))
app.post('/order/del', require('./api/order/del'));
app.get('/order/user', require('./api/order/user'))



// -----Comment-----
app.get('/comment/list', require('./api/comment/list'))
app.post('/comment/add', require('./api/comment/add'))
app.get('/comment/search', require('./api/comment/search'))
app.get('/comment/searchUser', require('./api/comment/searchUser'))
app.post('/comment/del', require('./api/comment/del'));


let imgSrc = [];

app.post('/api/upload', (req, res) => {
  var form = new formidable.IncomingForm();
    // 设置上传目录  绝对路径
    form.uploadDir = __dirname + '/public/img'
    form.parse(req,(err,fields,files)=>{
        if (!err){
            fs.rename(files.someExpressFiles.path, __dirname + '/public/img/' + files.someExpressFiles.name, (err)=>{
                if (!err){
                  imgSrc.push(`/img/${files.someExpressFiles.name}`)
                }else {
                    throw new Error(err)
                }
            })
        }else{
            throw new Error(err)
        }
    })
});

app.get('/img/list', function(req,res){
  res.json({
      code:1,
      msg: '获取列表成功',
      data: imgSrc[imgSrc.length-1]
  })
  res.end()
})


// -----TYPE-----
// 分类增加
app.post('/type/add',require('./api/type/add'))
// 分类列表
app.get('/type/list',require('./api/type/list'))
// 修改分类
app.get('/type/change',require('./api/type/change'))
// 删除分类
app.post('/type/del', require('./api/type/del'));
// 查询用户
app.get('/type/search', require('./api/type/search'))




// 查询包含此分类的景区
app.get('/search/type', require('./api/api/getTypeSec'))










// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
